package org.example.conrtoller;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import org.apache.commons.io.IOUtils;
import org.apache.poi.ss.formula.functions.Mode;
import org.apache.poi.ss.formula.functions.T;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.example.DictionaryService;
import org.example.Imp.DictionaryServiceImp;
import org.example.Imp.QuestionServiceImp;
import org.example.Imp.TeacherServiceImp;
import org.example.Imp.TemplateServiceImp;
import org.example.domain.Question;
import org.example.domain.Teacher;
import org.example.domain.Template;
import org.example.pageParam.CommonData;
import org.example.vo.PageVO;
import org.example.vo.QuestionVO;
import org.example.vo.TemplateVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RequestMapping("/template/")
@Controller
public class TemplateController {
    @Autowired
    private TeacherServiceImp teacherServiceImp;
    @Autowired
    private DictionaryServiceImp dictionaryServiceImp;
    @Autowired
    private TemplateServiceImp templateServiceImp;
    @Autowired
    private QuestionServiceImp questionServiceImp;
    @RequestMapping("addTemplate.html")
    public String addTemplate(Model model,HttpSession httpSession){
        model.addAttribute("allCourse",dictionaryServiceImp.queryAllCourse());
        List<Question> questionList = (List<Question>) httpSession.getAttribute("questionList");
        if (questionList == null){
            questionList = new ArrayList<Question>();
            httpSession.setAttribute("questionList",questionList);
        }
        List<QuestionVO> questionCache = new ArrayList<>();
        for (int i = 0 ;i<questionList.size();i++){
            questionCache.add(templateServiceImp.reverseVO(questionList.get(i),i+1));
        }
        System.out.println(questionList);
        model.addAttribute("currentQuestions",questionCache);
        model.addAttribute("allCourse",dictionaryServiceImp.queryAllCourse());
        return "template/addTemplate";
    }
    @RequestMapping("static/addQuestion.html")
    public String staticTemplateAddQuestion(){
        return "template/staticTemplateAddQuestion";
    }
    @RequestMapping("static/questionSave.html")
    public String questionSave(@RequestParam(value = "editTemplateId",required = false)String editTemplateId, Question question, HttpSession httpSession,Model model){
        Teacher teacher  =(Teacher) httpSession.getAttribute("loginTeacher");
        question.setTid(teacher.getId());
        List<Question> questionList = null;
        if (editTemplateId!=null && !editTemplateId.equals("")){
            //表示这次添加试题 时编辑页面的一个添加
            questionList = (List<Question>) httpSession.getAttribute("questionList"+editTemplateId);
            questionList.add(question);
        }else {
            questionList = (List<Question>) httpSession.getAttribute("questionList");
            if (questionList!=null){
                questionList.add(question);
            }else {
                questionList = new ArrayList<Question>();
                questionList.add(question);
                httpSession.setAttribute("questionList",questionList);
            }
        }

        List<QuestionVO> questionVOS = new ArrayList<>();
        if (editTemplateId!=null && !editTemplateId.equals("")){
            //表示是编辑页面需要回显数据
            List<Question> editQuestions = (List<Question>) httpSession.getAttribute("questionList"+editTemplateId);
            for (int i = 0;i<editQuestions.size();i++){
                QuestionVO questionVO = templateServiceImp.reverseVO(editQuestions.get(i),i+1);
                questionVOS.add(questionVO);
            }
        }else {
            QuestionVO questionVO = templateServiceImp.reverseVO(question,questionList.size());
            questionVOS.add(questionVO);
        }
        model.addAttribute("currentQuestions",questionVOS);
        String viewPath = null;
        if (editTemplateId!=null && !editTemplateId.equals("")){
            viewPath = "template/addTemplate";
            Template template = templateServiceImp.selectTemplateById(Long.parseLong(editTemplateId));
            model.addAttribute("allCourse",dictionaryServiceImp.queryAllCourse());
            TemplateVO templateVO = templateServiceImp.reverseVO(template);
            model.addAttribute("editTemplateVO",templateVO);
        }else {
            viewPath = "template/staticTemplateQuestions::staticTemplateQuestionList";
        }
        return viewPath;
    }
    @ResponseBody
    @RequestMapping("deleteQuestion")
    public void deleteQuestion(Integer index,@RequestParam(value = "editTemplateId",required = false) String editTemplateId,HttpSession httpSession){
        List<Question> questionList = null;
        if (editTemplateId!=null && !editTemplateId.equals("")){
            questionList =    (List<Question>) httpSession.getAttribute("questionList"+editTemplateId);
        }else {
            questionList =    (List<Question>) httpSession.getAttribute("questionList");
        }
        questionList.remove(index-1);
    }
    @ResponseBody
    @RequestMapping("deleteMoreQuestion")
    public void deleteMoreQuestion(String questionNumbers,HttpSession httpSession){//这个方法和上面那个方法可以合成一个  但是最近脑子不好使  所以写了两个
        String[] numbers = questionNumbers.split(",");
        List<Question> questionList =(List<Question>) httpSession.getAttribute("questionList");
        //删除时 会出现     0 1 2 3 4 5   删除了 2 3   变成了 0 1 2 3 4集合会出现向前移动的问题
        int tempLength = numbers.length;
        for (int i = 0 ;i<numbers.length;i++){
            questionList.remove(tempLength-1);
            tempLength = tempLength - 1;
        }
    }
    @ResponseBody
    @RequestMapping("static/selectQuestion")
    public QuestionVO selectQuestion(Integer number,HttpSession httpSession){
        List<Question> questionList =(List<Question>) httpSession.getAttribute("questionList");
        Question question = (Question) questionList.get(number - 1);
        return templateServiceImp.reverseVO(question,number);
    }
    @ResponseBody
    @RequestMapping("static/editSava")
    public void editSave(@RequestParam Map<String,Object> map,HttpSession httpSession){
        List<Question> questionList =(List<Question>) httpSession.getAttribute("questionList");
        Question question = (Question) questionList.get(Integer.parseInt((String) map.get("number"))-1);
        question.setLevel((String) map.get("level"));
        question.setType((String) map.get("type"));
        question.setSubject((String) map.get("content"));
        question.setAnswer((String) map.get("answer"));
        question.setOptions((String) map.get("options"));

    }
    @RequestMapping("staticFileUploadTemplate.html")
    public String uploadPage(){
        return "template/staticTemplateDownload";
    }
    @ResponseBody
    @RequestMapping("downloadTemplate.xlsx")
    public ResponseEntity<byte[]> downloadTemplate(){
        InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("downloadTemplate/staticTemplateQuestion.xlsx");
        byte[] bytes = null;
        HttpHeaders httpHeaders = null;
        try {
            bytes = new byte[inputStream.available()];
            IOUtils.read(inputStream,bytes);
            httpHeaders = new HttpHeaders();
            httpHeaders.add("content-disposition","attachment;filename=staticTemplate.xlsx");
            httpHeaders.add("content-type","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new ResponseEntity<>(bytes,httpHeaders, HttpStatus.OK);
    }

    @RequestMapping("importQuestionSubmit")
    public String importQuestionSubmit(MultipartFile file,String editTemplateId,HttpSession httpSession,Model model){
        Teacher loginTeacher = (Teacher)httpSession.getAttribute("loginTeacher");
        InputStream inputStream = null;
        List<QuestionVO> questionVOList = null;
        List<Question> questionList = null;
        if (editTemplateId!=null && !editTemplateId.equals("")){
            questionList = (List<Question>) httpSession.getAttribute("questionList"+editTemplateId);
        }else {
            questionList = (List<Question>) httpSession.getAttribute("questionList");
        }

        //首先需要将file转变为原生poi处理  为什么不用hutool提供的工具呢  因为有一些数据需要自己拼接
        StringBuilder failMessage = new StringBuilder();
        int failCount = 0;
        int successCount = 0;
        try {
            ExcelReader excelReader = ExcelUtil.getReader(file.getInputStream());
            Sheet sheet = excelReader.getSheet();
            //我们需要将sheet种每一个行进行处理
            i:for (int i = 2;i<=sheet.getLastRowNum();i++){
                Row row = sheet.getRow(i);//这个是一行数据   也就是道考题  需要对这个单独处理
                if(row == null){
                    continue i;
                }
                //因为所有的题型都有一些相似的处理 所以 这里单独处理一下
                Question question = new Question();
                String type = row.getCell(1).toString();
                String level = row.getCell(2).toString();
                String subject = row.getCell(3).toString();
                question.setType(type);
                question.setLevel(level);
                question.setSubject(subject);
                question.setTid(loginTeacher.getId());
                //选项  答案 这个需要单独处理
                if ("单选题".equals(type)){
                    //首先需要判断答案是否是26个大写字母
                    String answer = row.getCell(4).toString();
                    if (CommonData.COMMON_DICTIONARY.contains(answer)!=true){
                        //表示答案错误  就不需要做后续处理了
                        failCount++;
                        failMessage.append("第");
                        failMessage.append(row.getCell(0).toString().replace(".0",""));
                        failMessage.append("题，答案不正确|");
                        continue i;
                    }
                    question.setAnswer(answer+CommonData.COMMON_NORMAL_SEPARATOR);
                    //拼接选项
                    question.setOptions(row.getCell(5).toString()+CommonData.COMMON_NORMAL_SEPARATOR+row.getCell(6).toString()+CommonData.COMMON_NORMAL_SEPARATOR+row.getCell(7).toString()+CommonData.COMMON_NORMAL_SEPARATOR+row.getCell(8).toString()+CommonData.COMMON_NORMAL_SEPARATOR);
                }
                if ("多选题".equals(type)){
                    String[] answers = row.getCell(4).toString().split(",");
                    StringBuilder tempAnswer = new StringBuilder();
                    j:for (int j=0;j<answers.length;j++){
                        if (CommonData.COMMON_DICTIONARY.contains(answers[j])!=true){
                            //表示答案错误  就不需要做后续处理了
                            failCount++;
                            failMessage.append("第");
                            failMessage.append(row.getCell(0).toString().replace(".0",""));
                            failMessage.append("题，答案不正确|");
                            continue i;
                        }else {
                            tempAnswer.append(answers[j]);
                            tempAnswer.append(CommonData.COMMON_NORMAL_SEPARATOR);
                        }
                    }
                    question.setAnswer(tempAnswer.toString());
                    question.setOptions(row.getCell(5).toString()+CommonData.COMMON_NORMAL_SEPARATOR+row.getCell(6).toString()+CommonData.COMMON_NORMAL_SEPARATOR+row.getCell(7).toString()+CommonData.COMMON_NORMAL_SEPARATOR+row.getCell(8).toString()+CommonData.COMMON_NORMAL_SEPARATOR);
                }
                if ("判断题".equals(type)){
                    question.setAnswer(row.getCell(4).toString());
                    question.setOptions("正确"+CommonData.COMMON_NORMAL_SEPARATOR+"错误"+CommonData.COMMON_NORMAL_SEPARATOR);
                }
                if ("填空题".equals(type)){
                    //需要判断subject中【】的数量与答案中的数量问题
                    int blankCount = 0;
                    int index = subject.indexOf("【】");
                    String tempSubject = subject;
                    while (index!=-1){
                        blankCount++;
                        tempSubject = tempSubject.substring(index+2);
                        index = tempSubject.indexOf("【】");
                    }
                    String[] answers = row.getCell(4).toString().split(",");
                    StringBuilder stringBuilder = new StringBuilder();
                    for (int j = 0;j<answers.length;j++){
                        stringBuilder.append(answers[j]);
                        stringBuilder.append(CommonData.COMMON_NORMAL_SEPARATOR);
                    }
                    question.setOptions("无");
                    question.setAnswer(stringBuilder.toString());
                }
                if ("综合题".equals(type)){
                    question.setOptions("无");
                    question.setAnswer(row.getCell(4).toString());
                }
                successCount++;
                questionList.add(question);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        StringBuilder result = new StringBuilder();
        result.append("本次导入成功");
        result.append(successCount);
        result.append("道题;");
        result.append("失败");
        result.append(failCount);
        result.append("道题;");
        result.append("失败信息如下:");
        result.append(failMessage.toString());
        List<QuestionVO> questionCache = new ArrayList<>();
        for (int i = 0 ;i<questionList.size();i++){
            questionCache.add(templateServiceImp.reverseVO(questionList.get(i),i+1));
        }
        model.addAttribute("currentQuestions",questionCache);
        String viewPath = null;
        if (editTemplateId!=null && !editTemplateId.equals("")){
            viewPath = "template/addTemplate";
            Template template = templateServiceImp.selectTemplateById(Long.parseLong(editTemplateId));
            model.addAttribute("allCourse",dictionaryServiceImp.queryAllCourse());
            TemplateVO templateVO = templateServiceImp.reverseVO(template);
            model.addAttribute("editTemplateVO",templateVO);
        }else {
            viewPath = "template/staticTemplateQuestions";
        }
        model.addAttribute("message",result.toString());
        return viewPath;
    }
    @RequestMapping("cancelSave")
    @ResponseBody
    public void cancelSave(HttpSession httpSession){
        httpSession.setAttribute("questionList",new ArrayList<Question>());
    }
    @ResponseBody
    @RequestMapping("static/templateSave")
    public boolean templateSave(@RequestParam Map<String,String> param,HttpSession httpSession){
        Teacher teacher = (Teacher)httpSession.getAttribute("loginTeacher");
        Template template = new Template();
        List<Question> questionList = null;
        String editTemplateId = param.get("editTemplateId");
        if (editTemplateId!=null && !editTemplateId.equals("")){
            //编辑的模板保存
            template.setId(Long.parseLong(editTemplateId));
            questionList = (List<Question>) httpSession.getAttribute("questionList"+editTemplateId);
        }else {
            questionList = (List<Question>)httpSession.getAttribute("questionList");
        }
        template.setTid(teacher.getId());
        template.setStatus("私有");
        template.setName(param.get("name"));
        template.setTemplateType(param.get("type"));
        template.setTotal_score(Integer.parseInt(param.get("question_total_score").replace("分","")));
        template.setStatus(CommonData.COMMON_PRIVATE_STATUS);
        template.setYuliu1(param.get("course"));
        //需要对模板中试题的处理   因为我们没有单独做试题模块 所以 这里需要现将试题保存到数据库  因为 试题最终的存储格式：question1="2}-|-{1}-|-{2}-|-{3}-|-{
        //第一个是题型的分值  后面都是题号  但是因为试题没有存储到数据库所以 question没有id
        StringBuilder question1 = new StringBuilder();
        question1.append(param.get("question1_score")+CommonData.COMMON_NORMAL_SEPARATOR);
        StringBuilder question2 = new StringBuilder();
        question2.append(param.get("question1_score")+CommonData.COMMON_NORMAL_SEPARATOR);
        StringBuilder question3 = new StringBuilder();
        question3.append(param.get("question1_score")+CommonData.COMMON_NORMAL_SEPARATOR);
        StringBuilder question4 = new StringBuilder();
        question4.append(param.get("question1_score")+CommonData.COMMON_NORMAL_SEPARATOR);
        StringBuilder question5 = new StringBuilder();
        question5.append(param.get("question1_score")+CommonData.COMMON_NORMAL_SEPARATOR);

        for (int i =0;i<questionList.size();i++){
            Question question = questionList.get(i);
            question.setCourse(param.get("course"));
            question.setTid(teacher.getId());
            questionServiceImp.save(question);
            if ("单选题".equals(question.getType())){
                question1.append(question.getId()+""+CommonData.COMMON_NORMAL_SEPARATOR);
            }else if ("多选题".equals(question.getType())){
                question2.append(question.getId()+""+CommonData.COMMON_NORMAL_SEPARATOR);
            }else if ("判断题".equals(question.getType())){
                question3.append(question.getId()+""+CommonData.COMMON_NORMAL_SEPARATOR);
            }else if ("填空题".equals(question.getType())){
                question4.append(question.getId()+""+CommonData.COMMON_NORMAL_SEPARATOR);
            }else if ("综合题".equals(question.getType())){
                question5.append(question.getId()+""+CommonData.COMMON_NORMAL_SEPARATOR);
            }
        }
        template.setQuestion1(question1.toString());
        template.setQuestion2(question2.toString());
        template.setQuestion3(question3.toString());
        template.setQuestion4(question4.toString());
        template.setQuestion5(question5.toString());
        Boolean result = null;
        if (editTemplateId!=null && !editTemplateId.equals("")){
            //update操作
            result = templateServiceImp.editSave(template);
        }else{
            result = templateServiceImp.templateSave(template);
        }

        if (result){
            questionList.clear();
        }
        return result;
    }
    @RequestMapping("dynamic/save")
    @ResponseBody
    public boolean dynamicTemplateSave(@RequestParam Map<String,String> map,HttpSession httpSession){
        Teacher teacher = (Teacher)httpSession.getAttribute("loginTeacher");
        Template template = new Template();
        template.setName(map.get("name"));
        template.setTemplateType(map.get("type"));
        template.setTotal_score(Integer.parseInt(map.get("question_total_score")));
        template.setStatus(CommonData.COMMON_PRIVATE_STATUS);
        template.setTid(teacher.getId());
        template.setYuliu1(map.get("course"));
        template.setQuestion1(map.get("question1_score")+CommonData.COMMON_NORMAL_SEPARATOR+map.get("question1_simple_count")+CommonData.COMMON_NORMAL_SEPARATOR+map.get("question1_medium_count")+CommonData.COMMON_NORMAL_SEPARATOR+map.get("question1_difficult_count")+CommonData.COMMON_NORMAL_SEPARATOR);
        template.setQuestion2(map.get("question2_score")+CommonData.COMMON_NORMAL_SEPARATOR+map.get("question2_simple_count")+CommonData.COMMON_NORMAL_SEPARATOR+map.get("question2_medium_count")+CommonData.COMMON_NORMAL_SEPARATOR+map.get("question2_difficult_count")+CommonData.COMMON_NORMAL_SEPARATOR);
        template.setQuestion3(map.get("question3_score")+CommonData.COMMON_NORMAL_SEPARATOR+map.get("question3_simple_count")+CommonData.COMMON_NORMAL_SEPARATOR+map.get("question3_medium_count")+CommonData.COMMON_NORMAL_SEPARATOR+map.get("question3_difficult_count")+CommonData.COMMON_NORMAL_SEPARATOR);
        template.setQuestion4(map.get("question4_score")+CommonData.COMMON_NORMAL_SEPARATOR+map.get("question4_simple_count")+CommonData.COMMON_NORMAL_SEPARATOR+map.get("question4_medium_count")+CommonData.COMMON_NORMAL_SEPARATOR+map.get("question4_difficult_count")+CommonData.COMMON_NORMAL_SEPARATOR);
        template.setQuestion5(map.get("question5_score")+CommonData.COMMON_NORMAL_SEPARATOR+map.get("question5_simple_count")+CommonData.COMMON_NORMAL_SEPARATOR+map.get("question5_medium_count")+CommonData.COMMON_NORMAL_SEPARATOR+map.get("question5_difficult_count")+CommonData.COMMON_NORMAL_SEPARATOR);
        Boolean result = null;
        if (map.get("id")!=null && map.get("id")!=""){
            //编辑操作
            template.setId(Long.parseLong(map.get("id")));
            result = templateServiceImp.editSave(template);
        }else {
            //添加操作
            result = templateServiceImp.templateSave(template);
        }
        return result;
    }
    @RequestMapping("defaultTemplateList")
    public String templateList(String examSymbol,Model model,HttpSession httpSession,Map<String,Object> map){
        Teacher teacher = (Teacher)httpSession.getAttribute("loginTeacher");
        map.put("tid",teacher.getId());
        //需要将数据库中的模板进行查询展示 分页 过滤
        //但是有一个问题就是展示的模板是全部展示出来 还是只展示这个老师所拥有的模板（包括分享的模板）  我感觉是后者
        //首先需要查询关联的课程 作为页面展示
        model.addAttribute("allCourse",dictionaryServiceImp.queryAllCourse());
        //还需要查询分享老师（哪些老师分享模板给当前老师）
        model.addAttribute("shareTeachers",templateServiceImp.selectShareTeacher(new Long(teacher.getId())));
        //查询模板信息 因为这里很麻烦  需要很多的判断条件
        //想到了一个问题 因为页面查询有一个分享老师的过滤
        //如果选中这个  那么其他的过滤条件都因该在这个分享老师的模板中进行查找 如果没有选择分享老师  那么应该在当前老师的模板中  和其他老师共有的模板中查找
        model.addAttribute("pageVO",templateServiceImp.showTemplateList(CommonData.PAGE,CommonData.COUNT,map));
        model.addAttribute("currentTeacherId",teacher.getId());
        if (examSymbol!=null && !examSymbol.equals("")){
            //表示是考试页面中的管理模板需要的模板
            model.addAttribute("examSymbol","examSymbol");
        }
        return "template/templateList";
    }
    @RequestMapping("queryList.html")
    public String queryList(@RequestParam Map<String,Object> map,HttpSession httpSession,Model model){
        Teacher teacher = (Teacher)httpSession.getAttribute("loginTeacher");
        map.put("tid",teacher.getId());
        model.addAttribute("pageVO",templateServiceImp.showTemplateList(Integer.parseInt( (String) map.get("page")),CommonData.COUNT,map));
        model.addAttribute("currentTeacherId",teacher.getId());
        String examSymbol = (String)map.get("examSymbol");
        if (examSymbol!=null && !examSymbol.equals("")){
            model.addAttribute("examSymbol","examSymbol");
        }
        return "template/templateList::#template_list_body";
    }
    @RequestMapping("list/deleteOne")
    @ResponseBody
    public boolean deleteOneList(Long id,HttpSession httpSession){
        Teacher teacher = (Teacher)httpSession.getAttribute("loginTeacher");
        Template template = templateServiceImp.selectTemplateById(id);
        int count = templateServiceImp.selectTemplateShareCount(template.getId());
        if ("私有".equals(template.getStatus()) && teacher.getId().equals(template.getTid()) && count == 0){
            templateServiceImp.deleteOneList(id);
            return true;
        }else {
            return false;
        }
    }
    @ResponseBody
    @RequestMapping("list/setStatus")
    public int setStatus(@RequestParam Map<String,Object> map,HttpSession httpSession){
        Teacher teacher = (Teacher)httpSession.getAttribute("loginTeacher");
        map.put("tid",teacher.getId());
        //后面做到动态模板的试题抽取时  抽取的试题需要为公有 但是我没有做试题模块 所以 在模板模块时处理试题
        //当前模板的状态因为也是模板中试题的状态
        Template template = templateServiceImp.selectTemplateById(Long.parseLong((String) map.get("id")));
        List<Long> questionIds = new ArrayList<>();
        List<String> questions = new ArrayList<>();
        String question1 = template.getQuestion1();
        String question2 = template.getQuestion2();
        String question3 = template.getQuestion3();
        String question4 = template.getQuestion4();
        String question5 = template.getQuestion5();
        questions.add(question1);
        questions.add(question2);
        questions.add(question3);
        questions.add(question4);
        questions.add(question5);
        for (int i=0;i<questions.size();i++){
            String currentQuestion = questions.get(i);
            String[] split = currentQuestion.split(CommonData.COMMON_SEPARATOR);
            for (int j = 1;j<split.length;j++){
                questionIds.add(Long.parseLong(split[j]));
            }

        }
        templateServiceImp.updateTemplateRelationQuestionStatus(questionIds,(String)map.get("status"));
        return templateServiceImp.setTemplateStatus(map);
    }
    @RequestMapping("list/setShareStatus")
    @ResponseBody
    public int setShareStatus(Long id,String shareTeacherIds,HttpSession httpSession){
        Teacher teacher = (Teacher)httpSession.getAttribute("loginTeacher");
        Template template = templateServiceImp.selectTemplateById(id);
        if (template.getTid().equals(teacher.getId())){
            templateServiceImp.setShareStatus(id,shareTeacherIds);
            return 1;
        }else {
            return 0;
        }
    }
    @RequestMapping("list/shareTeacher.html")
    public String shareTeacher(Model model){
        PageVO pageVo = teacherServiceImp.showTeacherList(null, CommonData.PAGE, CommonData.COUNT);
        model.addAttribute("pageVO",pageVo);
        return "template/shareTeacherList";
    }
    @RequestMapping("list/select.html")
    public String shareTeacherSelect(String filterName,Integer page,Model model){
        PageVO pageVo = null;
        if (page==null){
            //说明可能是过滤查询
            pageVo = teacherServiceImp.showTeacherList(filterName, CommonData.PAGE, CommonData.COUNT);
        }else {
            //可能是分页查询
            pageVo = teacherServiceImp.showTeacherList(filterName,page, CommonData.COUNT);
        }
        model.addAttribute("pageVO",pageVo);
//        return "teacher/teacherMainPage::#teacherContextFragment";  //不知道为什么这样响应不了对应的片段
        return "template/shareTeacherList";
    }
    @RequestMapping("list/clearShareTeacher.html")
    public String clearShareTeacher(Model model){
        PageVO pageVo = teacherServiceImp.showTeacherList(null, CommonData.PAGE, CommonData.COUNT);
        model.addAttribute("pageVO",pageVo);
        return "template/shareTeacherList";
    }
    @RequestMapping("list/edit.html")
    public String edit(Long templateId,Model model,HttpSession httpSession){
        Template template = templateServiceImp.selectTemplateById(templateId);
        model.addAttribute("allCourse",dictionaryServiceImp.queryAllCourse());
        TemplateVO templateVO = templateServiceImp.reverseVO(template);
        model.addAttribute("editTemplateVO",templateVO);
        //动态模板的处理到此为止
        ArrayList<Question> questions = new ArrayList<>();
        List<Question> sessionQuestion = (List<Question>) httpSession.getAttribute("questionList"+templateId);
        if (sessionQuestion!=null && sessionQuestion.size()>0){
            //表明之前做过这个模板的编辑  可能修改了一些试题  需要再次展示之前的操作  这里只能做试题的修改 如果修改了模板名称  管理课程  暂时不作处理
            ArrayList<QuestionVO> questionVOS = new ArrayList<>();
            //将question变成页面展示的vo对象
            for(int i = 0;i<sessionQuestion.size();i++){
                questionVOS.add(templateServiceImp.reverseVO(sessionQuestion.get(i),i+1));
            }
            model.addAttribute("currentQuestions",questionVOS);
        }else {
            //下面这个if就是将templateVO中静态模板试题集合中的编号 变成question对象放在一个大集合中
            if (template.getTemplateType().equals("静态模板")) {
                //需要将question1-5需要变成question对象   页面展示需要变成questionVO对象
                {
                    List<Integer> templateQuestion1 = templateVO.getQuestion1_count();
                    for (int i =0;i<templateQuestion1.size();i++){
                        Question question = questionServiceImp.selectById(Long.parseLong(templateQuestion1.get(i)+""));
                        questions.add(question);
                    }
                }
                {
                    List<Integer> templateQuestion2 = templateVO.getQuestion2_count();
                    for (int i =0;i<templateQuestion2.size();i++){
                        Question question = questionServiceImp.selectById(Long.parseLong(templateQuestion2.get(i)+""));
                        questions.add(question);
                    }
                }
                {
                    List<Integer> templateQuestion3 = templateVO.getQuestion3_count();
                    for (int i =0;i<templateQuestion3.size();i++){
                        Question question = questionServiceImp.selectById(Long.parseLong(templateQuestion3.get(i)+""));
                        questions.add(question);
                    }
                }
                {
                    List<Integer> templateQuestion4 = templateVO.getQuestion4_count();
                    for (int i =0;i<templateQuestion4.size();i++){
                        Question question = questionServiceImp.selectById(Long.parseLong(templateQuestion4.get(i)+""));
                        questions.add(question);
                    }
                }
                {
                    List<Integer> templateQuestion5 = templateVO.getQuestion5_count();
                    for (int i =0;i<templateQuestion5.size();i++){
                        Question question = questionServiceImp.selectById(Long.parseLong(templateQuestion5.get(i)+""));
                        questions.add(question);
                    }
                }
            }
            ArrayList<QuestionVO> questionVOS = new ArrayList<>();
            //将question变成页面展示的vo对象
            for(int i = 0;i<questions.size();i++){
                questionVOS.add(templateServiceImp.reverseVO(questions.get(i),i+1));
            }
            model.addAttribute("currentQuestions",questionVOS);
            httpSession.setAttribute("questionList"+templateId,questions);
        }
        return "template/addTemplate";
    }
}

